import { getDefaultFormConfig ,setId ,overwrite} from "@/utils"
import { cloneDeep } from "lodash-es"
import { containers,basicFields } from "./widget/config"
/* 
    创建Form表单实例
*/
export const createFormDesigner =(VIns)=>{
    /* 
        VIns.$message 即饿了么的message消息弹窗
    */
    let defaultFormConfig = cloneDeep( getDefaultFormConfig() )

    return {
        VIns,
        widgetList:[],
        formConfig:{cssCode:""},
        selectId:null,
        selectWidget:null,
        selectWidgetName:null,
        formWidget:null, //表单设计器
        cssClassList:[], //自定义样式列表
        historyData:{ //历史记录前进和后退
            index:-1,
            maxStep:20,
            steps:[]
        },
        fieldValFun:new Map(), //字段引用map集合
        initDesigner(){
            this.widgetList = []
            this.formConfig = cloneDeep(defaultFormConfig)

            this.initHistoryData()
        },
        loadPresetCssCode(preCssCode) {
        },
        checkWidgetMove(evt) { 
            if (!!evt.dragged && !!evt.dragged.__draggable_context && !!evt.dragged.__draggable_context.element) {
                let wgCategory = evt.dragged.__draggable_context.element.category
                let wgType = evt.dragged.__draggable_context.element.type + ''
                if (!!evt.to) {
                    if ((evt.to.className === 'sub-form-table') && (wgCategory === 'container')) {
                    return false
                    }
                }
            }
            return true
        },
        /* 
            处理容器布局组件创建的时候，创建其内部组件,拷贝组件
        */
        copyNewContainerWidget(origin) {
            let newCon = cloneDeep(origin)
            newCon.id = newCon.type.replace(/-/g, '') + setId()
            newCon.options.name = newCon.id
            if (newCon.type === 'grid') {
                let newCol = cloneDeep( this.getContainerByType('grid-col') )
                let tmpId = setId()
                newCol.id = 'grid-col-' + tmpId
                newCol.options.name = 'gridCol' + tmpId
                newCon.cols.push(newCol)
                //
                newCol = cloneDeep(newCol)
                tmpId = setId()
                newCol.id = 'grid-col-' + tmpId
                newCol.options.name = 'gridCol' + tmpId
                newCon.cols.push(newCol)
            } else if (newCon.type === 'table') {
                let newRow = {cols: []}
                newRow.id = 'table-row-' + setId()
                newRow.merged = false
                let newCell = cloneDeep( this.getContainerByType('table-cell') )
                newCell.id = 'table-cell-' + setId()
                newCell.options.name = newCell.id
                newCell.merged = false
                newCell.options.colspan = 1
                newCell.options.rowspan = 1
                newRow.cols.push(newCell)
                newCon.rows.push(newRow)
            } else if (newCon.type === 'tab') {
                let newTabPane = cloneDeep( this.getContainerByType('tab-pane') )
                newTabPane.id = 'tab-pane-' + setId()
                newTabPane.options.name = 'tab1'
                newTabPane.options.label = 'tab 1'
                newCon.tabs.push(newTabPane)
            }
            //newCon.options.customClass = []
    
            delete newCon.options.displayName
            
            return newCon
        },
        checkFieldMove(evt){
            if (!!evt.dragged && !!evt.dragged.__draggable_context && !!evt.dragged.__draggable_context.element) {
                let wgCategory = evt.dragged.__draggable_context.element.category
                let wgType = evt.dragged.__draggable_context.element.type + ''
                if (!!evt.to) {
                    if ((evt.to.className === 'sub-form-table') && (wgType === 'slot')) {
                    //this.$message.info(this.vueInstance.i18nt('designer.hint.onlyFieldWidgetAcceptable'))
                    return false
                    }
                }
            }
    
            return true
        },
        /* 
            处理创建克隆组件
        */
        copyNewFieldWidget(origin){
            let newWidget = cloneDeep(origin)
            let newId = setId()
            newWidget.id = newWidget.type.replace(/-/g, '') + newId
            newWidget.options.name = newWidget.id
            newWidget.options.label = newWidget.options.label || newWidget.type.toLowerCase()
            delete newWidget.options.displayName
            return newWidget
        },  
        getContainerByType(typeName) {
            let allWidgets = [...containers, ...basicFields]
            let foundCon = null
            allWidgets.forEach((con) => {
            if (!!con.category && !!con.type && (con.type === typeName)) {
                foundCon = con
            }
            })
            return foundCon
        },
        registerFormWidget(formWidgetIns) {
            this.formWidget = formWidgetIns
        },
        setSelected(widget){
            if (!widget) {
                this.clearSelected()
                return
            }
            if (!!widget.id) {
                this.selectWidget = widget
                this.selectId = widget.id
                this.selectWidgetName = widget.options.name
            }
        },
        clearSelected(){
            this.selectWidget = null
            this.selectId = null
            this.selectWidgetName = null
        },
        clearDesigner(){
            // 清空设计器
            let emptyWidgetListFlag = this.widgetList.length === 0 //空的情况
            this.widgetList = []
            this.selectId = null
            this.selectWidgetName = null
            this.selectWidget = null
            overwrite(this.formConfig,defaultFormConfig)
            this.clearAllFieldFun()

            if(!emptyWidgetListFlag){
                // 存在组件情况下清空历史列表
                this.emitHistoryChange()
            }else{
                // 若组件为空，一直点击清楚画布，则不记录历史区域，直接走该分支
                this.saveCurrentHistoryStep()
            }           
        },
        initHistoryData(){
            // 初始化历史数据
            this.loadFormContentFromStorage()
            this.historyData.index++
            this.historyData.steps[this.historyData.index]={
                widgetList:cloneDeep(this.widgetList),
                formConfig:cloneDeep(this.formConfig)
            }
        },
        loadFormContentFromStorage(){
            // 加载本地数据
            let widgetListBackup = window.localStorage.getItem('widget__list__backup')
            if (!!widgetListBackup) {
                this.widgetList = JSON.parse(widgetListBackup)
            }
            let formConfigBackup = window.localStorage.getItem('form__config__backup')
            if (!!formConfigBackup) {
              //this.formConfig = JSON.parse(formConfigBackup)
              overwrite(this.formConfig, JSON.parse(formConfigBackup))  /* 用=赋值，会导致inject依赖注入的formConfig属性变成非响应式 */
            }
        },
        emitHistoryChange(){
            // 修改历史区域钱判断是否超出限制
            if(this.historyData.index === this.historyData.maxStep - 1){
                // 将旧数据出队
                this.historyData.steps.shift()
            }else {
                this.historyData.index++ //index代表当前历史区域内激活的位置
            }

            this.historyData.steps[this.historyData.index]={
                widgetList:cloneDeep(this.widgetList),
                formConfig:cloneDeep(this.formConfig)
            }
            this.saveFormContentToStorage()

            // 小于index历史数据需要展示出来，大于的不需要进行展示
            if(this.historyData.index < this.historyData.steps.length - 1 ){
                this.historyData.steps = this.historyData.steps.slice(0,this.historyData.index + 1)
            }
            console.log("emitHistoryChange",this.historyData);
        },
        saveCurrentHistoryStep(){ 
            this.historyData.steps[this.historyData.index]=cloneDeep({
                widgetList:this.widgetList,
                formConfig:this.formConfig
            })
            this.saveFormContentToStorage()
        },
        // 处理历史数据操作区前进后退按钮操作
        undoHistoryStep(){
            if(this.historyData.index !== 0){
                this.historyData.index--
            }
            // 将历史记录中的数据取出
            this.widgetList = cloneDeep(this.historyData.steps[this.historyData.index].widgetList)
            this.formConfig = cloneDeep(this.historyData.steps[this.historyData.index].formConfig)
            console.log("undoHistoryStep",this.historyData);
        },
        redoHistoryStep(){
            if(this.historyData.index !== this.historyData.steps.length - 1){
                this.historyData.index++
            }
            this.widgetList = cloneDeep(this.historyData.steps[this.historyData.index].widgetList)
            this.formConfig = cloneDeep(this.historyData.steps[this.historyData.index].formConfig)
            console.log("redoHistoryStep",this.historyData);
        },
        // 处理历史数据操作区域前进后退按钮禁用
        undoEnabled(){
            return this.historyData.index > 0 && this.historyData.steps.length > 0
        },
        redoEnabled(){
            return this.historyData.index < this.historyData.steps.length - 1
        },
        saveFormContentToStorage() {
            window.localStorage.setItem('widget__list__backup', JSON.stringify(this.widgetList))
            window.localStorage.setItem('form__config__backup', JSON.stringify(this.formConfig))
        },
        setFormJson(json) {
            json = typeof json === 'string' ? JSON.parse(json) : json
            this.widgetList = json.widgetList
            this.formConfig = json.formConfig
        },
        hasConfig(widget,originalPropName){
            // 查询当前组件中是否包含指定的配置项（需要从原始组件中查询）
            let originWidget = null;

            if(widget.category){
                // 容器组件
                originWidget = this.getContainerByType(widget.type)
            }else {
                originWidget = this.getFieldWidgetByType(widget.type)
            }

            if(!originWidget || !originWidget.options){
                return false
            }
            return Object.keys(originWidget.options).includes(originalPropName)
        },
        getFieldWidgetByType(type){
            let allWidgets = [...containers,...basicFields]
            return allWidgets.find(item=>{
                return  !item.category && item.type === type
            })
        },
        getContainerByType(type){
            let allWidgets = [...containers,...basicFields]
            return allWidgets.find(item=>{
                return  item.category && item.type === type
            })
        },
        createFieldValFun(id,fun){
            // 创建单个引用
            if(!this.fieldValFun.has(id))
                this.fieldValFun.set(id,fun)
        },
        clearAllFieldFun(){
            // 清空按钮触发清除所有引用
            this.fieldValFun = new Map()
        },
        clearFieldFunById(id){
            // 清除单个引用
            if(this.fieldValFun.has(id)){
                this.fieldValFun.delete(id)
            }
        },
        getCurFieldFunById(id){
            return this.fieldValFun.get(id)
        },
        setLayoutType(type){
            this.formConfig.layoutType = type
        },
        getLayoutType(){
            return this.formConfig.layoutType
        }
    }
}